﻿namespace PLCS.Shared.Common.Helper;

/// <summary>
/// 失败重试类
/// </summary>
public static class RetryHelper
{
    /// <summary>
    /// 同步方法
    /// </summary>
    /// <param name="action"></param>
    /// <param name="retryCount"></param>
    /// <param name="onFail"></param>
    /// <param name="delayMilliseconds"></param>
    /// <returns></returns>
    public static bool Retry(Func<bool> action, int retryCount, Action<int> onFail, int delayMilliseconds)
    {
        int retry = 0;
        while (retry < retryCount)
        {
            if (action())
                return true;

            retry++;
            onFail?.Invoke(retry);

            if (retry < retryCount)
                Thread.Sleep(delayMilliseconds);
        }

        return false;
    }

    /// <summary>
    /// 异步方法
    /// </summary>
    /// <param name="action"></param>
    /// <param name="retryCount"></param>
    /// <param name="onFail"></param>
    /// <param name="delayMilliseconds"></param>
    /// <returns></returns>
    public static async Task<bool> RetryAsync(Func<Task<bool>> action, int retryCount, Action<int> onFail, int delayMilliseconds)
    {
        int retry = 0;
        while (retry < retryCount)
        {
            if (await action())
                return true;

            retry++;
            onFail?.Invoke(retry);

            if (retry < retryCount)
                await Task.Delay(delayMilliseconds);
        }

        return false;
    }
}